package com.gitee.sys.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.mybase.top.entity.SysDept;
import com.gitee.sys.mapper.SysDeptMapper;
import com.gitee.sys.service.ISysDeptService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chengkaimao
 * @since 2018-11-17
 */
@Service
@Component
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {

    @Override
    public IPage<SysDept> getPage(long current, long size, SysDept sysDept) {
        IPage<SysDept> page = new Page<>(current, size);
        QueryWrapper<SysDept> sysUserQueryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(sysDept.getDeptCode())){
            sysUserQueryWrapper.like("dept_code", sysDept.getDeptCode());
        }
        if(StringUtils.isNotEmpty(sysDept.getDeptName())){
            sysUserQueryWrapper.like("dept_name", sysDept.getDeptName());
        }
        if(StringUtils.isNotEmpty(sysDept.getShopCode())){
            sysUserQueryWrapper.eq("shop_code", sysDept.getShopCode());
        }
        page = this.page(page, sysUserQueryWrapper);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveDept(SysDept sysDept) {
        sysDept.setCreateTime(LocalDateTime.now());
        sysDept.setIsLock(0);
        sysDept.setIsValid(1);
        return baseMapper.insert(sysDept);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDept(SysDept sysDept) {
        UpdateWrapper<SysDept> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("dept_code", sysDept.getDeptCode());
        updateWrapper.set("dept_name", sysDept.getDeptName());
        updateWrapper.set("is_parent", sysDept.getIsParent());
        updateWrapper.set("parent_code", sysDept.getParentCode());
        updateWrapper.set("shop_code", sysDept.getShopCode());
        updateWrapper.set("update_time", LocalDateTime.now());
        updateWrapper.eq("id", sysDept.getId());
        return baseMapper.update(sysDept, updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delDept(String deptCode) {
        QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dept_code", deptCode);
        return baseMapper.delete(queryWrapper);
    }
}
